package yxy.game.pm2.bean;

import org.joda.time.DateTime;
import org.redisson.api.RBucket;

import yxy.apple.util.redisson.RedisConnection;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.cherry.game.base.redis.RedisType;

public class ServerBean {

	// bean===========================================================================
	private int serverId;
	private int areaId;
	private DateTime starttime;

	public int getServerId() {
		return serverId;
	}

	public void setServerId(int serverId) {
		this.serverId = serverId;
	}

	public int getAreaId() {
		return areaId;
	}

	public void setAreaId(int areaId) {
		this.areaId = areaId;
	}

	public DateTime getStarttime() {
		return starttime;
	}

	public void setStarttime(DateTime starttime) {
		this.starttime = starttime;
	}

	// redis==========================================================================

	static public String key(int serverId) {
		return String.format("SERVER:%s", serverId);
	}

	static public String key(String serverId) {
		return String.format("SERVER:%s", serverId);
	}

	static private <V> RBucket<V> touch(String key) throws RedisException {
		RedisConnection redis = RedisManager.getInstance().getConnection(RedisType.REDIS_GAME);
		return RedisManager.client(redis).getBucket(key);
	}

	static public ServerBean get(String serverId) {
		try {
			RBucket<ServerBean> bucket = touch(key(serverId));
			ServerBean server = bucket.get();
			return server;
		} catch (RedisException e) {
			e.printStackTrace();
			return null;
		}
	}

	static public ServerBean get(int serverId) {
		try {
			RBucket<ServerBean> bucket = touch(key(serverId));
			ServerBean server = bucket.get();
			return server;
		} catch (RedisException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static ServerBean create(int serverId, int areaid, DateTime dt) {
		ServerBean server = new ServerBean();
		server.setServerId(serverId);
		server.setAreaId(areaid);
		server.setStarttime(dt);
		server.set();
		return server;
	}

	public void set() {
		try {
			RBucket<ServerBean> bucket = touch(key(getServerId()));
			bucket.set(this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
}
